package com.rc.saas.tenant.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * Created by sven on 2018-05-10
 */
public class Base64Util {
    /*字符集*/
    private static String DEFAULT_CHARSET = "UTF-8";

    private static final Logger logger = LoggerFactory.getLogger(Base64Util.class);

    public static byte[] encode(byte[] bytes) {
        return Base64.getEncoder().encode(bytes);
    }

    public static String encode(String text, String charset) {
        try {
            return Base64.getEncoder().encodeToString(text.getBytes(charset));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static String encode(String text) {
        return encode(text, DEFAULT_CHARSET);
    }

    public static String encodeBytesToString(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] decode(byte[] bytes) {
        return Base64.getDecoder().decode(bytes);
    }

    public static String decode(String text, String charset) {
        try {
            return new String(Base64.getDecoder().decode(text), charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static String decode(String text) {
        return decode(text, DEFAULT_CHARSET);
    }

    public static byte[] decodeStringToBytes(String text) {
        return Base64.getDecoder().decode(text);
    }

}
